<?php

class Maindomin extends Module
{
	/** @var max image size */
	protected $maxImageSize = 307200;

	function __construct()
	{
		$this->name = 'maindomin';
		$this->tab = 'Tools';
		$this->version = '1.5';
		
		parent::__construct();
		
		$this->displayName = $this->l('Select your Main Domin Name');
		$this->description = $this->l('Select your Main Domin Name - phpskill.com');
	}

	function install()
	{
		if (!Configuration::updateValue('MAIN_DOMIN_NEED_WWW', 1) OR !parent::install())
			return false;
		return $this->registerHook('header');
	}
	
	public function getContent()
	{
		$output = '<h2>'.$this->displayName.'</h2>';
		if (Tools::isSubmit('submitMainDomin'))
		{//var_dump();
			$is_www_need = intval(Tools::getValue('www_need'));
			if ($is_www_need)
				Configuration::updateValue('MAIN_DOMIN_NEED_WWW', 1);
			else
				Configuration::updateValue('MAIN_DOMIN_NEED_WWW', 0);
		}
		return $output.$this->displayForm();
	}

	public function displayForm()
	{
		$output = '
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
			<fieldset><legend><img src="'.$this->_path.'logo.gif" alt="" title="" />'.$this->l('Settings').'</legend>
				<label>'.$this->l('Domin name need www?').'</label>
				<div class="margin-form">
					<input type="checkbox" name="www_need" value="1" '.((Configuration::get('MAIN_DOMIN_NEED_WWW')) ? ' checked="checked"' : '' ).' />
				</div>
				<center><input type="submit" name="submitMainDomin" value="'.$this->l('Save').'" class="button" /></center>
			</fieldset>
		</form>';
		return $output;
	}

	function hookHeader($params)
	{
		$protocol = ($_SERVER['SERVER_PORT'] == 80) ? 'http' : 'https';
		if($_SERVER['HTTP_HOST'] != 'localhost'){
			if(substr($_SERVER['HTTP_HOST'],0,4) == 'www.' && !Configuration::get('MAIN_DOMIN_NEED_WWW'))
				header('Location:'.$protocol.'://'.substr($_SERVER['HTTP_HOST'],4));
			else if(substr($_SERVER['HTTP_HOST'],0,3) != 'www' && Configuration::get('MAIN_DOMIN_NEED_WWW'))
				header('Location:'.$protocol.'://www.'.$_SERVER['HTTP_HOST']);
		}
	}

}
